import Compressor from 'compressorjs';
import { base64toFile, blobToBase64 } from '@/assets/js/utils/fileTransform';
// 只能对jpeg格式的图片进行转换
/**
 * @param image 图片 base64格式
 * @param backType 需要返回的类型blob,file
 * @param quality 图片压缩比 0-1,数字越小，图片压缩越小
 * @returns
 */
interface ICompressor {
    // imageBase64和imageFile参数二选一
    imageBase64?: any; //图片 base64格式
    imageFile?: any; //图片 文件对象
    backType?: 'file' | 'blob' | 'base64'; //需要返回的类型blob,file；默认返回file
    quality?: number; //图片压缩比 0-1,数字越小，图片压缩越小
    maxWidth?: number; //图片最大宽度
}

export function imageCompressor(data: ICompressor) {
    return <any>new Promise(async (resolve, reject) => {
        if (!data.imageBase64 && !data.imageFile) {
            reject('请传入图片文件');
        }
        let image: any;
        if (data.imageBase64) {
            image = base64toFile(data.imageBase64);
        } else if (data.imageFile) {
            image = data.imageFile;
        }
        image = await convertImage(image, data.maxWidth);
        //如未传入quality参数，则对文件大小判断自动设置
        let autoQuality = 1;
        //1m的大小
        let oneMegabyte = 1024 * 1024;
        if (image.size < oneMegabyte * 0.2) {
            //小于0.2M
            autoQuality = 1;
        } else if (image.size < oneMegabyte) {
            //小于1M
            autoQuality = 0.85;
        } else if (image.size < 2 * oneMegabyte) {
            //小于2M
            autoQuality = 0.75;
        } else if (image.size < 3 * oneMegabyte) {
            //小于3M
            autoQuality = 0.65;
        } else if (image.size < 5 * oneMegabyte) {
            //小于5M
            autoQuality = 0.5;
        } else if (image.size < 10 * oneMegabyte) {
            //小于10M
            autoQuality = 0.3;
        } else {
            //大于10M
            autoQuality = 0.1;
        }

        new Compressor(image, {
            quality: data.quality || autoQuality,
            async success(result) {
                let file = new File([result], image.name, { type: image.type });
                if (!data.backType || data.backType == 'file') {
                    resolve(file);
                } else if (data.backType == 'blob') {
                    resolve(result);
                } else if (data.backType == 'base64') {
                    let base64Res = await blobToBase64(result);
                    resolve(base64Res);
                } else {
                    resolve(file);
                }
            },
            error(err) {
                console.log('图片压缩失败---->>>>>', err);
                reject(err);
            }
        });
    });
}

// 思路是创建一个图片，将file等于这个图片，然后创建一个canvas图层 ，将canvas等比例缩放，
//然后用canvas的drawImage将图片与canvas合起来，再把canvas的base64转成file即可
function convertImage(file: any, maxWidth: any) {
    return new Promise((resolve, reject) => {
        const fileName = file.name.substring(0, file.name.indexOf('.'));
        let reader = new FileReader(); //读取file
        reader.readAsDataURL(file);
        reader.onloadend = function (e: any) {
            let image: any = new Image(); //新建一个img标签（还没嵌入DOM节点)
            image.src = e.target.result; //将图片的路径设成file路径
            image.onload = function () {
                // 设置最大宽度；高度自适应
                const maxWidthSize = maxWidth || 750;
                // 当前图片尺寸
                let { width, height } = image;
                // 最大尺寸计算
                if (width > maxWidthSize) {
                    height = Math.floor(height * (maxWidthSize / width));
                    width = maxWidthSize;
                }
                let canvas = document.createElement('canvas'),
                    context: any = canvas.getContext('2d'),
                    imageWidth = width,
                    imageHeight = height,
                    data = '';
                canvas.width = imageWidth;
                canvas.height = imageHeight;

                context.drawImage(image, 0, 0, imageWidth, imageHeight);
                data = canvas.toDataURL('image/jpeg');
                var newfile = base64toFile(data, fileName + '.jpg');
                resolve(newfile);
            };
        };
    });
}
